package com.jyb.qiyefuwu.view.activity.usercenter;


import android.app.Dialog;
import android.content.Intent;
import android.graphics.Paint;
import android.graphics.drawable.Drawable;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.core.util.Pair;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.bitmap.CenterCrop;
import com.bumptech.glide.load.resource.bitmap.RoundedCorners;
import com.bumptech.glide.request.RequestOptions;
import com.jyb.qiyefuwu.R;
import com.jyb.qiyefuwu.databinding.ActivityPurchaseOrderDetailsBinding;
import com.jyb.qiyefuwu.entity.OderDetailsEntity;
import com.jyb.qiyefuwu.entity.ServiceNodeBean;
import com.jyb.qiyefuwu.eventmodel.MakOverOrderDeleteItemEvent;
import com.jyb.qiyefuwu.uitls.DialogFunction;
import com.jyb.qiyefuwu.uitls.DialogHelper;
import com.jyb.qiyefuwu.uitls.DialogTextReturnValue;
import com.jyb.qiyefuwu.uitls.PointUtils;
import com.jyb.qiyefuwu.uitls.TextViewBindingAdapter;
import com.jyb.qiyefuwu.view.dialog.OderNodeDialog;
import com.jyb.qiyefuwu.viewmodel.SaleListViewModel;
import com.jyb.qiyefuwu.viewmodel.SalesOderDetailsModel;
import com.sgb.link.constant.RequestCode;
import com.sgb.link.router.PathEnterpriseServices;
import com.sgb.link.router.PathUser;
import com.swgk.core.base.aroute.AppRouteConstant;
import com.swgk.core.base.model.entity.ContactsEntitiy;
import com.swgk.core.base.model.entity.InvoicingInfoEntity;
import com.swgk.core.common.base.BaseActivity;
import com.swgk.core.common.utils.ActivityJump;
import com.swgk.core.customview.ItemInputTextView;
import com.swgk.core.util.ClickUtils;
import com.swgk.core.util.DateUtils;
import com.swgk.core.util.DensityUtils;
import com.swgk.core.util.MToast;
import com.swgk.core.util.SharedPreferenceUtil;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.List;


/**
 * 作者:陈方凯
 * 日期:2021/09/27
 * 说明:采购订单详情
 */
@Route(path = PathEnterpriseServices.PurchaseOrderDetailsActivity)
public class PurchaseOrderDetailsActivity extends BaseActivity<SalesOderDetailsModel, ActivityPurchaseOrderDetailsBinding> implements ItemInputTextView.OnWholeItemClickListener {
    public static final int TRADE_MARK = 110119;//商标
    public static final int PATENT = 110118;//专利
    public static final int COPYRIGHT = 110117;//版权
    public static final int APPLY_PAY = 1156;//申请付款
    public static final int MARK = 1157;//备注
    public static final int CONTACTS = 1158;//联系人
    public static final int INVOICE = 1159;//发票
    /**
     * 0删除   1关闭   2取消   3接单 4确认完成
     */
    private int operationOrder;
    /**
     * TRADE_MARK商标   PATENT专利   COPYRIGHT版权
     */
    private Integer zhiChanType;
    private String oderId;
    private String type;
    private OderNodeDialog oderNodeDialog;
    private SaleListViewModel saleListViewModel;
    private List<ServiceNodeBean> serviceNodeBean;
    private OderDetailsEntity mData;
    private int roleType;


    @Override
    protected int layoutId() {
        return R.layout.activity_purchase_order_details;
    }

    @Override
    protected void createViewModel() {
        mViewModel = new ViewModelProvider(this).get(SalesOderDetailsModel.class);
        saleListViewModel = new ViewModelProvider(this).get(SaleListViewModel.class);
        EventBus.getDefault().register(this);
    }

    @Override
    protected void init() {
        saleListViewModel.buyerOrSeller = 1;
        zhiChanType = getIntent().getIntExtra("zhiChanType", 110118);
        oderId = getIntent().getStringExtra("oderId");
        roleType = SharedPreferenceUtil.getInstance().getSaveIntData(SharedPreferenceUtil.COM_TYPE, 1);
        observer();
        initData();
        initListen();
    }

    private void initListen() {
        mBinding.tvOrderPay.setOnClickListener(this);
        mBinding.tvCancelOder.setOnClickListener(this);//取消订单
        mBinding.tvDeleteOder.setOnClickListener(this);//删除订单
        mBinding.llFoldPersonInfo.setOnClickListener(this);//个人信息展开
        mBinding.llFoldOderInfo.setOnClickListener(this);//订单信息展开
        mBinding.llFoldInvoiceInfo.setOnClickListener(this);//开票信息展开
        mBinding.tvCheckPerson.setOnClickListener(this);//切换联系人
        mBinding.tvCheckInvoice.setOnClickListener(this);//选择发票
        mBinding.llMark.setOnClickListener(this);//修改备注
        mBinding.lookProgress.setOnClickListener(this);
        mBinding.backView.setOnClickListener(this);
        mBinding.rvGoTo.setOnClickListener(this);
        mBinding.itvDatabase.setOnWholeItemClickListener(this);
        mBinding.itvJournal.setOnWholeItemClickListener(this);
        mBinding.itvVoucher.setOnWholeItemClickListener(this);
        mBinding.imageTalkIm.setOnClickListener(this);
        mBinding.tvLookMsg.setOnClickListener(this);
        mBinding.tvConfirmCompletion.setOnClickListener(this);
    }

    private void initData() {
        mBinding.tvMark.setEnable(false);
        mBinding.tvIsSeller.setText("卖方");//买卖方
        mBinding.tvTitle.setText("采购订单详情");//买卖方
        mBinding.tvOrderPay.setText(roleType == 1 ? "申请付款" : "立即支付");
        mBinding.itvDatabase.setArrowRightImage(R.mipmap.icn_right_blue);
        mBinding.itvVoucher.setArrowRightImage(R.mipmap.icn_right_blue);
        getDetails();
    }

    private void observer() {
        mViewModel.oderData.observe(this, new Observer<OderDetailsEntity>() {
            @Override
            public void onChanged(OderDetailsEntity data) {
                mData = data;
                mViewModel.process(mViewModel.oderData.getValue().getId());
                setNetData(data);
            }
        });
        mViewModel.dataText.observe(this, new Observer<String>() {
            @Override
            public void onChanged(String s) {
                mBinding.tvEndTime.setText(s);
            }
        });
        mViewModel.checkData.observe(this, new Observer<String>() {
            @Override
            public void onChanged(String s) {
                MToast.showToast(PurchaseOrderDetailsActivity.this, "修改成功");
//                mViewModel.removeTimer();
                getDetails();
            }
        });

        mViewModel.nodeList.observe(this, new Observer<List<ServiceNodeBean>>() {
            @Override
            public void onChanged(List<ServiceNodeBean> serviceNodeBeans) {
                serviceNodeBean = serviceNodeBeans;
                oderNodeDialog = null;
                if ("3".equals(mData.getOrderStatus())) {
                    mBinding.tvEndTime.setText(serviceNodeBean.get(serviceNodeBean.size() - 1).getTips());
                    setDrawable(false);
                }
            }
        });
        saleListViewModel.mToast.observe(this, new Observer<String>() {
            @Override
            public void onChanged(String s) {
                MToast.showToast(PurchaseOrderDetailsActivity.this, s);
                getDetails();
            }
        });
    /*    saleListViewModel.payStatus.observe(this, new Observer<String>() {
            @Override
            public void onChanged(String s) {
                mBinding.tvStatus.setText("交易中");
                saleListViewModel.orderStatus = 2;
                mBinding.tvCancelOder.setVisibility(View.GONE);//取消订单按钮
                mBinding.tvOrderPay.setVisibility(View.GONE);//立即支付按钮
                serviceNodeBean = null;
            }
        });*/
        saleListViewModel.delete_item.observe(this, new Observer<Long>() {
            @Override
            public void onChanged(Long aLong) {
                EventBus.getDefault().post(new MakOverOrderDeleteItemEvent(aLong));
                switch (operationOrder) {
                    case 0:
                        MToast.showToast(PurchaseOrderDetailsActivity.this, "删除成功");
                        finish();
                        break;
                    case 1:
//                        MToast.showToast(PurchaseOrderDetailsActivity.this, "订单已取消");
//                        mViewModel.removeTimer();
                        mBinding.tvEndTime.setText("买方主动取消订单");
                        getDetails();//刷新详情
                        break;
                    case 2:
//                        MToast.showToast(PurchaseOrderDetailsActivity.this, "订单已关闭");
//                        mViewModel.removeTimer();
                        mBinding.tvEndTime.setText("买方主动关闭订单");
                        getDetails();//刷新详情
                        break;
                    case 3:
                        MToast.showToast(PurchaseOrderDetailsActivity.this, "接单成功");
                        getDetails();//刷新详情
                        finish();
                        break;
                    case 4:
                        getDetails();//刷新详情
                        break;
                }
            }
        });
        saleListViewModel.delete_fail.observe(this, id -> {
            EventBus.getDefault().post(new MakOverOrderDeleteItemEvent(id));
            finish();
//            getDetails();
        });
        saleListViewModel.closeFail.observe(this, id -> {
            EventBus.getDefault().post(new MakOverOrderDeleteItemEvent(id));
//            finish();
            getDetails();
        });
        saleListViewModel.mToast.observe(this, new Observer<String>() {
            @Override
            public void onChanged(String s) {
                MToast.showToast(PurchaseOrderDetailsActivity.this, s);
            }
        });
        saleListViewModel.approvestats.observe(this, type -> {
            switch (type) {
                case -2:
                    DialogHelper.showDialog(this, "申请提示", "该订单付款需要进行审批，是否提交付款申请？", "取消", "确定", new DialogFunction() {
                        @Override
                        public void normalRoundDialog() {
                            /**
                             * 订单id  资产类型  收款方  价格  下单时间
                             */
                            ActivityJump.startActivityForResult(PurchaseOrderDetailsActivity.this, APPLY_PAY, PathEnterpriseServices.ApplyForPaymentActivity,
                                    Pair.create("oderId", oderId),
                                    Pair.create("zhiChanType", zhiChanType),
                                    Pair.create("sellerName", mViewModel.oderData.getValue().getSellerName()),
                                    Pair.create("price", mViewModel.oderData.getValue().getDealPrice()),
                                    Pair.create("createTime", mViewModel.oderData.getValue().getOrderTime()),
                                    Pair.create("id", saleListViewModel.applyId),
                                    Pair.create("publishType", mViewModel.oderData.getValue().getPublishType()),
                                    Pair.create("sellerNo", mViewModel.oderData.getValue().getSellerNo()),
                                    Pair.create("agentNo", mViewModel.oderData.getValue().getAgentNo()),
                                    Pair.create("agent", mViewModel.oderData.getValue().getAgent()));
                        }
                    });
                    break;


                case 3:
                case -1:
                    DialogHelper.showDialog(this, "审批中", "该订单已申请付款，审批通过后才可付款。", "", "确定", new DialogFunction() {
                        @Override
                        public void normalRoundDialog() {

                        }
                    });
                    break;
                case 0://审批被拒绝
                    DialogHelper.showDialog(this, "提交审核", "该订单付款申请未通过审批，是否再次发起申请？", "取消", "确定", new DialogFunction() {
                        @Override
                        public void normalRoundDialog() {
                            /**
                             * 订单id  资产类型  收款方  价格  下单时间
                             */
                            ActivityJump.startActivityForResult(PurchaseOrderDetailsActivity.this, APPLY_PAY, PathEnterpriseServices.ApplyForPaymentActivity,
                                    Pair.create("oderId", oderId),
                                    Pair.create("zhiChanType", zhiChanType),
                                    Pair.create("sellerName", mViewModel.oderData.getValue().getSellerName()),
                                    Pair.create("price", mViewModel.oderData.getValue().getDealPrice()),
                                    Pair.create("createTime", mViewModel.oderData.getValue().getOrderTime()),
                                    Pair.create("id", saleListViewModel.applyId),
                                    Pair.create("publishType", mViewModel.oderData.getValue().getPublishType()),
                                    Pair.create("sellerNo", mViewModel.oderData.getValue().getSellerNo()),
                                    Pair.create("agentNo", mViewModel.oderData.getValue().getAgentNo()),
                                    Pair.create("agent", mViewModel.oderData.getValue().getAgent()));
                        }
                    });
                    break;
                case 2:
                case 1://审批通过
                    DialogHelper.showDialog(this, "审批通过", "", "", "企业用户支付请前往“资金中心-待付账单”处理", "", "我知道了", new DialogFunction() {
                        @Override
                        public void normalRoundDialog() {

                        }
                    });
                    break;
                case 4:
                    DialogHelper.showDialog(this, "申请付款", "确认提交付款申请？提交成功后，可在资金中心-待付账单进行支付",
                            "特别说明：确认支付该订单，若支付后，出现因买方原因而造成异常订单，一律由买方承担违约金（包括且不限于卖方损失费用、三方支付平台手续费等）。",
                            "取消", "确定", new DialogFunction() {
                                @Override
                                public void normalRoundDialog() {
                                    saleListViewModel.CreatePayOrder(1);
                                }
                            });
                    break;

                case 5:
                    DialogHelper.showDialog(this, "提示", "", "付款申请已提交", "企业用户支付请前往“资金中心-待付账单”处理", "", "我知道了", new DialogFunction() {
                        @Override
                        public void normalRoundDialog() {

                        }
                    });

                    break;
                case 6:
                    /*DialogHelper.showDialog(this, "提示", "", "管理员已经开启订单付款审批流程", "企业用户支付请前往“资金中心-待付账单”处理", "", "我知道了", new DialogFunction() {
                        @Override
                        public void normalRoundDialog() {

                        }
                    });*/
                    MToast.showLongToast(PurchaseOrderDetailsActivity.this, "管理员已经开启订单付款审批流程");
                    break;


            }
        });
    }

    private void setNetData(OderDetailsEntity data) {
        try {
            //联系人信息
            mBinding.tvContacts.setText(data.getContactName());//联系人
            mBinding.tvContactNumber.setText(data.getContactPhone());//联系电话
            mBinding.tvAddress.setText(data.getProvinceName() + data.getCityName() + data.getAreaName() + data.getAddress());//联系地址
            mBinding.tvZipCode.setText(data.getPostCode());//邮政编码
            mBinding.tvCompanyName.setText(data.getCompanyName());//公司名称
            mBinding.tvPosition.setText(data.getPosition());//职位
            //订单信息
            mBinding.tvOderNo.setText(data.getOrderId());//订单编号
            mBinding.tvBuyerAndSeller.setText(data.getSellerName());//买卖方
            mBinding.tvPayType.setText("在线支付");//支付方式
            mBinding.tvHandler.setText(data.getAgent());//经办人
            mBinding.tvOderTime.setText(DateUtils.stampToDate(data.getOrderTime()));//下单时间
            mBinding.tvAllPrice.setText(TextViewBindingAdapter.setMoneyForRMB("￥" + PointUtils.price(Double.valueOf(data.getDealPrice()))));
            mBinding.tvMark.setEditContent(data.getComment());//备注
            mBinding.tvMark.setShowBottomNumber(false);
            mBinding.tvMark.setHint("/");
            //订单状态码 1待接单 2待支付 3已关闭 4交易中 5交易完成
            switch (data.getOrderStatus()) {
                case "1":
                    mBinding.tvStatus.setText("待接单");
                    mBinding.tvCancelOder.setVisibility(View.VISIBLE);//取消
                    mBinding.tvDeleteOder.setVisibility(View.GONE);//删除
                    mBinding.tvCheckPerson.setVisibility(View.VISIBLE);//选择联系人
                    mBinding.tvCheckInvoice.setVisibility(View.VISIBLE); //选择发票
                    mBinding.llMark.setVisibility(View.VISIBLE);//编辑备注
                    saleListViewModel.orderStatus = 1;
                    mBinding.tvEndTime.setText("等待卖方接单");
                    setDrawable(false);
                    break;
                case "2":
                    mBinding.tvStatus.setText("待付款");
                    saleListViewModel.orderStatus = 2;
                    mBinding.tvCancelOder.setVisibility(View.VISIBLE);//取消订单按钮
                    mBinding.tvOrderPay.setVisibility(View.VISIBLE);//立即支付按钮
                    mViewModel.timeBefore(data.getExpirationTime(), "后自动关闭订单", data.getSystemTime());
                    setDrawable(true);
                    break;
                case "3":
                    mBinding.tvStatus.setText("已关闭");
                    saleListViewModel.orderStatus = 3;
                    mBinding.tvCancelOder.setVisibility(View.GONE); //取消
                    mBinding.tvOrderPay.setVisibility(View.GONE);//立即支付按钮
                    mBinding.tvDeleteOder.setVisibility(View.VISIBLE);//删除
                    mBinding.llMark.setVisibility(View.GONE);//编辑备注
                    mBinding.tvCheckPerson.setVisibility(View.GONE);//切换联系人
                    mBinding.tvCheckInvoice.setVisibility(View.GONE);//选择开票信息
                    break;
                case "4":
                    mBinding.tvStatus.setText("交易中");
                    saleListViewModel.orderStatus = 4;
                    mBinding.tvInvoiceMsg.setText("开票记录");
                    mBinding.tvCancelOder.setVisibility(View.GONE); //取消订单按钮
                    mBinding.tvOrderPay.setVisibility(View.GONE);//立即支付按钮
                    mBinding.tvCheckPerson.setVisibility(View.GONE);//切换联系人
                    mBinding.itvVoucher.setVisibility(View.VISIBLE);
                    mBinding.llMark.setVisibility(View.GONE);//编辑备注
                    if (data.getProcessStatus().equals("4")) {
                        mBinding.tvConfirmCompletion.setVisibility(View.VISIBLE);
                        mBinding.rvMsg.setVisibility(View.VISIBLE);
                        mViewModel.timeBefore(data.getExpirationTime(), "后自动完成订单", data.getSystemTime());
                    } else {
                        mBinding.tvConfirmCompletion.setVisibility(View.GONE);
                        mBinding.tvEndTime.setText("等待卖方提交凭证");
                        setDrawable(false);
                    }
                    break;
                case "5":
                    mBinding.tvStatus.setText("已完成");
                    saleListViewModel.orderStatus = 5;
                    mBinding.tvInvoiceMsg.setText("开票记录");
                    mBinding.tvConfirmCompletion.setVisibility(View.GONE);
                    mBinding.tvEndTime.setVisibility(View.GONE);
                    mBinding.rvMsg.setVisibility(View.GONE);
                    mBinding.llMark.setVisibility(View.GONE);//编辑备注
                    mBinding.tvCheckPerson.setVisibility(View.GONE);//切换联系人
                    mBinding.itvVoucher.setVisibility(View.VISIBLE);
                    RelativeLayout.LayoutParams lp = (RelativeLayout.LayoutParams) mBinding.tvStatus.getLayoutParams();
                    lp.topMargin = DensityUtils.dip2px(this, 16);
                    mBinding.tvStatus.setLayoutParams(lp);
                    break;
            }
            //发票信息
            mBinding.tvInvoiceTitle.setText(data.getInvoiceTitle());//开票抬头
            mBinding.tvInvoiceNumber.setText(data.getNumber());//税号
            mBinding.tvBankOfDeposit.setText(data.getBank());//开户银行
            mBinding.tvBankNo.setText(data.getBankAccount());//银行账号
            mBinding.tvCompanyAddress.setText(data.getCompanyAddress());//企业地址
            mBinding.tvCompanyPhone.setText(data.getTel());//企业电话
            //知产信息
            String img = "";//知产图片
            int imgId = R.mipmap.image_order_list_defuntimage;
            //知产图片
            if (zhiChanType == TRADE_MARK) {
                img = data.getTrademarkImg();//商标图片
                mBinding.name.setText("商标名称：" + data.getTradeMarkName());//商标名称
                mBinding.tvType1.setText("商标分类：" + data.getTrademarkClassification());//商标分类
                mBinding.tvType2.setText("商标注册号：" + data.getTradeMarkRegistration());//商标注册号
                type = "商标";
            } else if (zhiChanType == PATENT) {
                //专利
                img = data.getPatentImg();
                mBinding.name.setText("专利名称：" + data.getPatentName());//专利名称
                mBinding.tvType1.setText("专利类型：" + data.getPatentClassification());//专利类型
                mBinding.tvType2.setText("专利注册号：" + data.getPatentRegistration());//专利注册号
                type = "专利";
                switch (data.getPatentClassification()) {
                    case "发明专利":
                        imgId = R.mipmap.qiyefuwu_module_famingzhuanli_for_patent_publish;
                        break;
                    case "实用新型":
                        imgId = R.mipmap.qiyefuwu_module_shiyongxinxing_patent_publish;
                        break;
                    case "外观设计":
                        imgId = R.mipmap.qiyefuwu_module_waiguansheji_patent_publish;
                        break;
                }
            } else if (zhiChanType == COPYRIGHT) {
                //版权
                img = data.getCopyrightImg();
                mBinding.name.setText("版权名称：" + data.getCopyrightName());//版权名称
                mBinding.tvType1.setText("版权分类：" + data.getClassificationCopyright());//版权分类
                mBinding.tvType2.setText("登记号：" + data.getCopyrightNumber());//登记号
                type = "版权";
            }
            //知产图片
            Glide.with(PurchaseOrderDetailsActivity.this)
                    .load(img)
                    .error(imgId)
                    .apply(new RequestOptions().transforms(new CenterCrop(), new RoundedCorners(2)))
                    .into(mBinding.img);//图标
            if (data.getOrderClassification().equals("2")) {
                mBinding.tvBargainingPrice.setVisibility(View.VISIBLE);
                mBinding.tvBargainingPrice.getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG | Paint.ANTI_ALIAS_FLAG); // 设置中划线并加清晰
                mBinding.tvBargainingPrice.setText("￥" + PointUtils.price(Double.valueOf(data.getTransferPrice())));
                mBinding.tvPrice.setText("￥" + PointUtils.price(Double.valueOf(data.getDealPrice())));
                mBinding.imageYj.setVisibility(View.VISIBLE);
            } else {
                mBinding.tvBargainingPrice.setVisibility(View.GONE);
                mBinding.tvPrice.setText(TextViewBindingAdapter.setMoneyForRMB("￥" + PointUtils.price(Double.valueOf(data.getTransferPrice()))));//转让价格
                mBinding.imageYj.setVisibility(View.GONE);
            }
            mBinding.tvCount.setText("x" + data.getAmount());//数量
        } catch (Exception e) {
            Log.e("销售订单详情", "数据异常");
        }
    }

    /**
     * 详情接口
     */
    private void getDetails() {
        //销售订单传2  采购订单传1
        mViewModel.removeTimer();
        if (zhiChanType == TRADE_MARK) {
            mViewModel.tradeMark(oderId, 1);
        } else if (zhiChanType == PATENT) {
            mViewModel.patent(oderId, 1);
        } else if (zhiChanType == COPYRIGHT) {
            mViewModel.copyrigh(oderId, 1);
        }
    }


    /**
     * 设置展开隐藏
     */
    private void setFold(ImageView imageView, TextView textView, LinearLayout linearLayout) {
        int gone = linearLayout.getVisibility();
        imageView.setImageResource(gone == View.GONE ? R.mipmap.icn_shouqi : R.mipmap.icn_zhankai);
        textView.setText(gone == View.GONE ? "收起" : "展开");
        linearLayout.setVisibility(gone == View.GONE ? View.VISIBLE : View.GONE);
    }

    /**
     * 查看流程节点
     */
    private void showOderNodeDialog(List<ServiceNodeBean> serviceNodeBeans) {
        if (oderNodeDialog == null) {
            oderNodeDialog = new OderNodeDialog(this, serviceNodeBeans);
        }
        oderNodeDialog.show();
    }

    /**
     * 切换联系人
     *
     * @param data
     */
    private void checkContacts(ContactsEntitiy data) {
        mViewModel.contactData.setAddress(data.getAddress());
        mViewModel.contactData.setAreaCode(data.getAreaCode());
        mViewModel.contactData.setAreaName(data.getAreaName());
        mViewModel.contactData.setCityCode(data.getCityCode());
        mViewModel.contactData.setCityName(data.getCityName());
        mViewModel.contactData.setCompanyName(data.getCompanyName());
        mViewModel.contactData.setContactId(data.getId() + "");
        mViewModel.contactData.setContactName(data.getContactName());
        mViewModel.contactData.setContactPhone(data.getContactPhone());
        mViewModel.contactData.setOrderId(mViewModel.oderData.getValue().getId());
        mViewModel.contactData.setPosition(data.getPosition());
        mViewModel.contactData.setPostCode(data.getPostCode());
        mViewModel.contactData.setProvinceCode(data.getProvinceCode());
        mViewModel.contactData.setProvinceName(data.getProvinceName());
        mViewModel.saveOrUpdate();
    }

    /**
     * 切换发票
     *
     * @param data
     */
    private void checkInvoice(InvoicingInfoEntity data) {
        mViewModel.invoiceData.setBank(data.getBank());
        mViewModel.invoiceData.setBankAccount(data.getBankAccount());
        mViewModel.invoiceData.setInvoiceId(data.getId() + "");
        mViewModel.invoiceData.setInvoiceTitle(data.getCompanyName());
        mViewModel.invoiceData.setNumber(data.getNumber());
        mViewModel.invoiceData.setOrderId(mViewModel.oderData.getValue().getId());
        mViewModel.invoiceData.setTel(data.getTel());
        mViewModel.billingInformation();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case CONTACTS:
                if (RequestCode.CODE_ZERO == resultCode && data.getSerializableExtra("data") != null) {
                    checkContacts((ContactsEntitiy) data.getSerializableExtra("data"));
                }
                break;
            case INVOICE:
                if (RequestCode.CODE_ZERO == resultCode && data.getSerializableExtra("data") != null) {
                    checkInvoice((InvoicingInfoEntity) data.getSerializableExtra("data"));
                }
                break;
            case MARK:
                if (RequestCode.CODE_ZERO == resultCode && data.getSerializableExtra("data") != null) {
                    mBinding.tvMark.setEditContent((String) data.getSerializableExtra("data"));
                }
                break;
            case APPLY_PAY:
                if (RequestCode.CODE_ZERO == resultCode) {//采购订单-提交审批回调
//                    finish();
                    /*mBinding.tvStatus.setText("交易中");
                    saleListViewModel.orderStatus = 2;
                    mBinding.tvCancelOder.setVisibility(View.GONE);//取消订单按钮
                    mBinding.tvOrderPay.setVisibility(View.GONE);//立即支付按钮*/
                    getDetails();
                } else if (RequestCode.CODE_ONE == resultCode) {
                    getDetails();
                }
                break;
        }
    }

    @Override
    public void onMultiClick(View v) {
        int id = v.getId();
        if (id == R.id.tv_order_pay) {
            //立即支付
            // TODO: 2021/10/19
            gotoPay();
        } else if (id == R.id.tv_cancel_oder) {
            //取消订单
            oderCancel();
        } else if (id == R.id.tv_delete_oder) {
            //删除订单
            oderDelete();
        } else if (id == R.id.ll_fold_person_info) {
            //展开收起
            setFold(mBinding.imgFoldPersonInfo, mBinding.tvFoldPersonInfo, mBinding.llGonePerson);
        } else if (id == R.id.ll_fold_oder_info) {
            //展开收起
            setFold(mBinding.imgFoldOderInfo, mBinding.tvFoldOderInfo, mBinding.llGoneOder);
        } else if (id == R.id.ll_fold_invoice_info) {
            //展开收起
            setFold(mBinding.imgFoldInvoiceInfo, mBinding.tvFoldInvoiceInfo, mBinding.llGoneInvoice);
        } else if (id == R.id.tv_check_person) {
            //切换联系人
            ActivityJump.startActivityForResult(PurchaseOrderDetailsActivity.this, CONTACTS, PathUser.ContanctsActivity, Pair.create("request", true));
        } else if (id == R.id.tv_check_invoice) {
            if ("4".equals(mViewModel.oderData.getValue().getOrderStatus()) || "5".equals(mViewModel.oderData.getValue().getOrderStatus())) {
                //查看开票记录
                ActivityJump.startActivity(PathEnterpriseServices.BillingRecordActivity, Pair.create("oderId", oderId),
                        Pair.create("isGone", true), Pair.create("status", mViewModel.oderData.getValue().getProcessStatus()));
            } else {
                //选择发票信息
                ActivityJump.startActivityForResult(PurchaseOrderDetailsActivity.this, INVOICE, PathUser.ReceIptActivity);
            }

        } else if (id == R.id.ll_mark) {
            //备注跳转
            ActivityJump.startActivityForResult(PurchaseOrderDetailsActivity.this, MARK, PathEnterpriseServices.SetMarkActivity, Pair.create("mark", mBinding.tvMark.getEditContent()), Pair.create("id", mViewModel.oderData.getValue().getId()));
        } else if (id == R.id.look_progress) {
            //查看进度
            if (serviceNodeBean == null) {

            } else {
                showOderNodeDialog(serviceNodeBean);
            }
        } else if (id == R.id.back_view) {
            finish();
        } else if (id == R.id.rv_go_to) {
            //详情跳转
            if (!ClickUtils.isDoubleClick()) {
                ActivityJump.startActivity(AppRouteConstant.ZiChan.ZICHAN_MAKEOVERDETAILACTIVITY, Pair.create("id", Long.valueOf(mViewModel.oderData.getValue().getDetailsId())), Pair.create("detail", type));
            }
        } else if (id == R.id.image_talk_im) {
            MToast.showLongToast(this, "功能开发中，敬请期待!");
        } else if (id == R.id.tv_look_msg) {
            ActivityJump.startActivity(PathEnterpriseServices.VoucherActivity, Pair.create("oderId", oderId),
                    Pair.create("isGone", true), Pair.create("status", mViewModel.oderData.getValue().getProcessStatus()),Pair.create("isList", false));
        } else if (id == R.id.tv_confirm_completion) {
            DialogHelper.showDialog(this, new DialogFunction() {
                @Override
                public void normalRoundDialog() {
                    operationOrder = 4;
                    saleListViewModel.oderDetailsEntity = mViewModel.oderData.getValue();
                    saleListViewModel.confirmOderComplete(1);
                }
            });
        }
    }

    @Override
    public void OnWholeItemClick(View view) {
        int id = view.getId();
        if (id == R.id.itv_database) {
            ActivityJump.startActivity(PathEnterpriseServices.DatabaseActivity, Pair.create("id", mViewModel.oderData.getValue().getId()),
                    Pair.create("buyerOrSeller", 0),
                    Pair.create("orderstatus", mViewModel.oderData.getValue().getOrderStatus())
            );
        } else if (id == R.id.itv_journal) {
//            MToast.showToast(this, "请前往PC端登录查看");
        } else if (id == R.id.itv_voucher) {
            //查看凭证记录
            ActivityJump.startActivity(PathEnterpriseServices.VoucherActivity, Pair.create("oderId", oderId),
                    Pair.create("isGone", true), Pair.create("status", mViewModel.oderData.getValue().getProcessStatus()),Pair.create("isList", false));
        }
    }


    /**
     * 取消订单
     */
    private void oderCancel() {
        DialogHelper.showDialog(PurchaseOrderDetailsActivity.this, "取消订单", true, "请输入取消订单的原因", 200, true, new DialogTextReturnValue() {
            @Override
            public void returnvalue(String value, Dialog dialog) {
                dialog.dismiss();
                operationOrder = 1;
                saleListViewModel.ColoseOrder(mViewModel.oderData.getValue().getId() + "", value, false);
            }
        });
    }

    /**
     * 删除订单
     */
    private void oderDelete() {
        DialogHelper.showDialog(PurchaseOrderDetailsActivity.this, "温馨提示", "是否删除该订单？", "取消", "确定", new DialogFunction() {
            @Override
            public void normalRoundDialog() {
                operationOrder = 0;
                saleListViewModel.deleteOrder(mViewModel.oderData.getValue().getId());
            }
        });
    }

    /**
     * 显示隐藏 时间icn
     */
    private void setDrawable(boolean time) {
        if (time) {
            Drawable drawable = getResources().getDrawable(R.mipmap.icn_biao);
            drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
            mBinding.tvEndTime.setCompoundDrawables(drawable, null, null, null);
        } else {
            mBinding.tvEndTime.setCompoundDrawables(null, null, null, null);
        }
    }

    private void gotoPay() {
        saleListViewModel.oderDetailsEntity = mViewModel.oderData.getValue();
        if (roleType == 1) {
            //企业
            saleListViewModel.getOrderStatus(1);
        } else {
            //个人或者团队
            DialogHelper.showDialog(this, "重要提示", "确认支付该订单，若支付后，出现因买方原因而造成异常订单，一律由买方承担违约金（包括且不限于卖方损失费用、三方支付平台手续费等）。", "不了，我再看看", "明白，仍要支付", new DialogFunction() {
                @Override
                public void normalRoundDialog() {
                    saleListViewModel.CreatePayOrderForUser(1);
                }
            });
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void updatepayEvent(Object o) {
        if (o == null) {
            return;
        }
        JSONObject jsonObject = JSON.parseObject(JSON.toJSONString(o));
        if (jsonObject.get("code") != null) {
            int code = jsonObject.getInteger("code");
            switch (code) {
                case 1000000013:
                case 1000000014:
                case 2://收银台返回的code
                    if (!ClickUtils.isDoubleClick() && code == 2) {
                        getDetails();
                    }
                    break;
            }

        }

    }



    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().removeStickyEvent(this);
    }
}
